"use strict";

const axios = require("axios");
const urlJoin = require("url-join");
const semver = require("semver");
const log = require("@test-cli/log");

function getNpmInfo(npmName, registry) {
  if (!npmName) {
    return null;
  }

  const registryUrl = registry || getDefaultRegistry();
  const npmInfoPath = urlJoin(registryUrl, npmName);

  return axios
    .get(npmInfoPath)
    .then(res => {
      if (res.status === 200) {
        return res.data;
      } else {
        return null;
      }
    })
    .catch(e => {
      log.verbose("npmName", `${npmName} package ${e.message}`);
      return Promise.reject(e);
    });
}

// 获取npm所有版本
async function getNpmVersions(npmName, registry) {
  const data = await getNpmInfo(npmName, registry);
  if (data) {
    return Object.keys(data.versions);
  } else {
    return [];
  }
}

// 获取默认npm地址
function getDefaultRegistry(isOriginal = false) {
  return isOriginal
    ? "https://registry.npmjs.org/"
    : "https://registry.npm.taobao.org/";
}

// 获取大于 baseVersion 的版本
function getSemverVersions(baseVersion, versions) {
  versions = versions
    .filter(version => semver.satisfies(version, `^${baseVersion}`))
    .sort((a, b) => semver.gt(b, a));

  return versions;
}

// 获取最新的版本号
async function getNpmSemverVersions(baseVersion, npmName, registry) {
  const versions = await getNpmVersions(npmName, registry);
  const newVersions = await getSemverVersions(baseVersion, versions);
  if (newVersions && newVersions.length > 0) {
    return newVersions[0];
  }

  return null;
}

async function getNpmLatestVersion(npmName, registry) {
  const versions = await getNpmVersions(npmName, registry);
  if (versions) {
    return versions.sort((a, b) => semver.gt(b, a))[0];
  } else {
    return null;
  }
}

module.exports = {
  getNpmInfo,
  getNpmVersions,
  getNpmSemverVersions,
  getDefaultRegistry,
  getNpmLatestVersion
};
